package com.zhai.domain.strategy.service.armory;

import com.zhai.domain.strategy.model.entity.StrategyAwardEntity;
import com.zhai.domain.strategy.service.armory.algorithm.AbstractAlgorithm;
import com.zhai.domain.strategy.service.armory.algorithm.IAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @Description: 策略装配
 * @ClassName: StrategyArmoryDispatch
 * @Author: zhaiyongxin
 * @Date: 2025/6/30 13:16
 * @Version: 1.0
 */
@Slf4j
@Service("strategyArmoryDispatch")
public class StrategyArmoryDispatch extends AbstractStrategyAlgorithm{

    private Map<String, IAlgorithm> algorithmMap;

    private final Integer ALGORITHM_THRESHOLD_VALUE = 10000;

    public StrategyArmoryDispatch(Map<String, IAlgorithm> algorithmMap) {
        this.algorithmMap = algorithmMap;
    }


    /**
     * 装配算法
     *
     * @param key                   为策略ID、权重ID
     * @param strategyAwardEntities 对应的奖品概率
     */
    @Override
    protected void armoryAlgorithm(String key, List<StrategyAwardEntity> strategyAwardEntities) {
        BigDecimal minAwareRate = minAwareRate(strategyAwardEntities);
        double rateRange = convert(minAwareRate);
        if (rateRange <= ALGORITHM_THRESHOLD_VALUE) {
            IAlgorithm o1Algorithm = algorithmMap.get(AbstractAlgorithm.Algorithm.O1.getKey());
            o1Algorithm.armoryAlgorithm(key, strategyAwardEntities, new BigDecimal(rateRange));
            repository.cacheStrategyArmoryAlgorithm(key, AbstractAlgorithm.Algorithm.O1.getKey());
        } else {
            IAlgorithm o1Algorithm = algorithmMap.get(AbstractAlgorithm.Algorithm.OLogN.getKey());
            o1Algorithm.armoryAlgorithm(key, strategyAwardEntities, new BigDecimal(rateRange));
            repository.cacheStrategyArmoryAlgorithm(key, AbstractAlgorithm.Algorithm.OLogN.getKey());
        }
    }

    /**
     * 调度算法抽奖
     *
     * @param key
     * @return
     */
    @Override
    protected Integer dispatchAlgorithm(String key) {
        String beanName = repository.queryStrategyArmoryAlgorithmFromCache(key);
        if (beanName == null) {
            throw new RuntimeException("key " + key + " beanName is " + beanName);
        }
        IAlgorithm iAlgorithm = algorithmMap.get(key);
        return iAlgorithm.dispatchAlgorithm(key);
    }
}
